<?php


namespace app\service\user;


use app\model\user\UserModel;
use app\model\user\UserMoneyDetailModel;
use app\service\BaseService;

class UserMoneyDetailService extends BaseService
{

    public function __construct()
    {
        $this->model = new UserMoneyDetailModel();
    }

    const INVITE_USER_BUY = 1;
    const WITHDRAW_BACK = 2;


    const WITHDRAW = 101;
    const APPLY_ACTIVE = 102;
    const APPLY_DRIVE = 103;
    const APPLY_PARTNER_DRIVE = 104;
    const APPLY_STUDY = 105;
    const APPLY_CHECK = 106;


    protected $typeArr = [
        // 余额增加
        self::INVITE_USER_BUY => '成功邀请好友%s下单',

        self::WITHDRAW => '提现',
        self::APPLY_ACTIVE => '活动报名',
        self::APPLY_DRIVE => '试驾报名',
        self::APPLY_PARTNER_DRIVE => '陪驾报名',
        self::APPLY_STUDY => '学车报名',
        self::APPLY_CHECK => '验车报名',
    ];


    public function getTypeArr()
    {
        return $this->typeArr;
    }

    public function getTypeText($key)
    {
        $arr = $this->typeArr;
        return isset($arr[$key]) ? $arr[$key] : '未知类型';
    }

    public function createLog($title, $userId, $type, $amount, $relatedUid, $orderSn, $remark = '')
    {
        $userInfo = UserModel::lock('lock in share mode')->where('id', $userId)->find();
        if (!$userInfo) {
            return true;
        }
        $before = $userInfo['money'];
        $after = $type > 100 ? bcsub($before, $amount, 2) : bcadd($before, $amount, 2);
        $userInfo->money = $after;
        $userInfo->save();

        $model = clone $this->model;
        $model->title = $title;
        $model->user_id = $userId;
        $model->type = $type;
        $model->before = $before;
        $model->amount = $amount;
        $model->after = $after;
        $model->related_uid = $relatedUid;
        $model->order_sn = $orderSn;
        $model->remark = $remark;
        $model->save();
        return true;
    }
}